package com.algernoon.rpc.springrpc.rmi.natives;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.algernoon.rpc.springrpc.entity.User;

@RestController
public class RmiController {
	
	Logger logger = LoggerFactory.getLogger(RmiController.class);
	
	private IUserService userService;
	
	@PostConstruct
	public void init() {
			try {
				// 在RMI服务注册表中查找名称为IUserService的对象
				userService = (IUserService) Naming.lookup("rmi://localhost:8888/UserService");
			} catch (MalformedURLException | RemoteException | NotBoundException e) {
				logger.error("获取远程rmi服务异常！");
				e.printStackTrace();
			}
	}
	
	@GetMapping("/native/rmi/user/{id}")
	@ResponseBody
	public User findUserById(@PathVariable Integer id) {
		logger.info("[findUserById] request param id is {}.", id);
		return userService.findUserById(id);
	}

}
